package com.boyuan.huijiaoyu;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baoyz.swipemenulistview.SwipeMenu;
import com.baoyz.swipemenulistview.SwipeMenuCreator;
import com.baoyz.swipemenulistview.SwipeMenuItem;
import com.baoyz.swipemenulistview.SwipeMenuListView;
import com.baoyz.swipemenulistview.SwipeMenuListView.OnMenuItemClickListener;
import com.boyuan.huijiaoyu.R;
import com.magicsoft.constant.Constant;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.ttcaca.cas.android.client.utils.Helper;

public class DownloadManagerActivity extends BaseActivity implements
		OnClickListener {

	private RelativeLayout btnBack;
	private TextView txt_title;

	File directory = new File(Constant.DOWNLOAD_DIRECT);
	private DownloadAdapter mAdapter;
	private SwipeMenuListView mListView;
	private List<String> items = null;
	private List<String> paths = null;// 存放当前目录所有文件路径
	private ImageLoader mImageLoader;
	DisplayImageOptions options;
	private String backtitle;

	/**
	 * Title: onCreate Description:
	 * 
	 * @param savedInstanceState
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_download_manager);
		initUI();
	}

	private void initUI() {
		Intent intent = getIntent();
		backtitle = intent.getStringExtra("backtitle");
		mImageLoader = ImageLoader.getInstance();
		options = new DisplayImageOptions.Builder()
				.showImageOnLoading(R.drawable.ic_stub)
				.showImageForEmptyUri(R.drawable.ic_empty)
				.showImageOnFail(R.drawable.ic_error).cacheInMemory(true)
				.cacheOnDisc(true).considerExifParams(true)
				.bitmapConfig(Bitmap.Config.RGB_565).build();
		mImageLoader.clearMemoryCache();
		mImageLoader.clearDiskCache();

		TextView tvback = (TextView) findViewById(R.id.tv_myback);
		tvback.setText(backtitle);
		btnBack = (RelativeLayout) findViewById(R.id.myback);
		btnBack.setOnClickListener(this);

		txt_title = (TextView) findViewById(R.id.txt_title);
		txt_title.setText("下载列表");

		mListView = (SwipeMenuListView) findViewById(R.id.download_listview);
		getFileDir(directory);
		// step 1. create a MenuCreator
		SwipeMenuCreator creator = new SwipeMenuCreator() {

			@Override
			public void create(SwipeMenu menu) {
				// create "delete" item
				SwipeMenuItem deleteItem = new SwipeMenuItem(
						getApplicationContext());
				// set item background
				deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9,
						0x3F, 0x25)));
				// set item width
				deleteItem.setWidth(dp2px(90));
				// set a icon
				deleteItem.setIcon(R.drawable.ic_delete);
				// add to menu
				menu.addMenuItem(deleteItem);
			}
		};
		// set creator
		mListView.setMenuCreator(creator);
		// step 2. listener item click event
		mListView.setOnMenuItemClickListener(new OnMenuItemClickListener() {
			@Override
			public boolean onMenuItemClick(int position, SwipeMenu menu,
					int index) {
				Helper.delAllFile(paths.get(position));
				items.remove(position);
				paths.remove(position);
				mAdapter.notifyDataSetChanged();
				return false;
			}
		});

		mListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				String path = paths.get(position);
				Log.e("setOnItemClickListener", "path:" + path);
				File file = new File(path);
				Intent fileIntent = Helper.getFileIntent(file);
				startActivity(fileIntent);
				isBackIntoTheFrontDesk = true;
			}
		});
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.myback:
			finish();
			break;
		default:
			break;
		}
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		if (isBackIntoTheFrontDesk) {
			isBackIntoTheFrontDesk = false;
		}
		super.onResume();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	@Override
	public void backClicked() {
		isBackAllowed = true;
	}

	private void getFileDir(File f) {
		if (items == null) {
			items = new ArrayList<String>();
			paths = new ArrayList<String>();
		} else {
			items.clear();
			paths.clear();
		}
		// 排序
		File[] files = sortFiles(f);

		if (files != null) {
			for (int i = files.length-1; i >=0; i--) {
				File file = files[i];
				items.add(file.getName());
				paths.add(file.getPath());
			}
			mAdapter = new DownloadAdapter(this, items, paths);
			mListView.setAdapter(mAdapter);
		}
	}

	/**
	 * 
	 * @param f
	 *            按修改时间排序文件夹下文件并返回数组
	 * @return
	 */
	private File[] sortFiles(File f) {
		File[] files = f.listFiles();
		if (files != null) {
			Pair[] pairs = new Pair[files.length];
			for (int i = 0; i < files.length; i++)
				pairs[i] = new Pair(files[i]);
			
			// Sort them by timestamp.
			Arrays.sort(pairs);
			
			// Take the sorted pairs and extract only the file part, discarding the
			// timestamp if modify meanwhile.
			for (int i = 0; i < files.length; i++)
				files[i] = pairs[i].f;
		}
		return files;
	}

	class Pair implements Comparable<Pair> {
		public long t;
		public File f;

		public Pair(File file) {
			f = file;
			t = file.lastModified();
		}

		public int compareTo(Pair p) {
			long u = p.t;
			return t < u ? -1 : t == u ? 0 : 1;
		}
	};

	private int dp2px(int dp) {
		return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
				getResources().getDisplayMetrics());
	}

	class DownloadAdapter extends BaseAdapter {

		private LayoutInflater mInflater;
		private List<String> items;
		private List<String> paths;

		private static final int TYPE_PDF = 0;
		private static final int TYPE_AUDIO = 1;
		private static final int TYPE_VIDEO = 2;
		private static final int TYPE_IMAGE = 3;
		private static final int TYPE_APP = 4;
		private static final int TYPE_OTHERS = 9;

		public DownloadAdapter(Context context, List<String> it, List<String> pa) {
			mInflater = LayoutInflater.from(context);
			items = it;
			paths = pa;
		}

		@Override
		public int getCount() {
			return items.size();
		}

		@Override
		public Object getItem(int position) {
			return items.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			ViewHolder holder;
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.file_row, null);
				holder = new ViewHolder();
				holder.text = (TextView) convertView.findViewById(R.id.text);
				holder.icon = (ImageView) convertView.findViewById(R.id.icon);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			try {
				File f = new File(paths.get(position).toString());
				holder.text.setText(f.getName());
				if (f.isDirectory()) {
					mImageLoader.displayImage("drawable://"
							+ R.drawable.folder, holder.icon, options, null,
							null);
				} else {
					switch (Helper.getFileIntType(f)) {
					case TYPE_PDF:
						mImageLoader.displayImage("drawable://"
								+ R.drawable.doc, holder.icon, options, null,
								null);
						break;
					case TYPE_AUDIO:
						mImageLoader.displayImage("drawable://"
								+ R.drawable.icon_audio, holder.icon, options,
								null, null);
						break;
					case TYPE_VIDEO:
						mImageLoader.displayImage("drawable://"
								+ R.drawable.icon_video, holder.icon, options,
								null, null);
						break;
					case TYPE_IMAGE:
						String uri = "file:///" + f.getPath();
						mImageLoader.displayImage(uri, holder.icon, options,
								null, null);
						break;
					case TYPE_APP:
						mImageLoader.displayImage("drawable://"
								+ R.drawable.icon_apk, holder.icon, options,
								null, null);
						break;
					case TYPE_OTHERS:
						mImageLoader.displayImage("drawable://"
								+ R.drawable.icon_others, holder.icon, options,
								null, null);
						break;
					default:
						mImageLoader.displayImage("drawable://"
								+ R.drawable.doc, holder.icon, options, null,
								null);
						break;
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return convertView;
		}

		private class ViewHolder {
			TextView text;
			ImageView icon;
		}

	}

}
